﻿#include "date.h"

#include <chrono>
#include <sstream>
#include <iomanip>

namespace breaking
{
	date::date()
	{
		m_msec = 0;
	}

	date::date(const time& _time)
	{
		// 将秒时间戳转换为time_t
		std::time_t s_time = _time.sec();

		// 使用localtime转换为tm结构
		m_tm = *std::localtime(&s_time);
		m_msec = (int32_t)(_time.msec() % 1000);
	}

	date::~date()
	{
	}

	time date::to_time() const
	{
		return (uint64_t)mktime((std::tm*)&m_tm) * 1000 + m_msec;
	}

	int32_t date::year() const
	{
		return m_tm.tm_year + 1900;
	}

	void date::year(int32_t _year)
	{
		m_tm.tm_year = _year - 1900;
	}

	int32_t date::month() const
	{
		return m_tm.tm_mon + 1;
	}

	void date::month(int32_t _month)
	{
		m_tm.tm_mon = _month - 1;
	}

	int32_t date::day() const
	{
		return m_tm.tm_mday;
	}

	void date::day(int32_t _day)
	{
		m_tm.tm_mday = _day;
	}

	int32_t date::hour() const
	{
		return m_tm.tm_hour;
	}

	void date::hour(int32_t _hour)
	{
		m_tm.tm_hour = _hour;
	}

	int32_t date::minute() const
	{
		return m_tm.tm_min;
	}

	void date::minute(int32_t _minute)
	{
		m_tm.tm_min = _minute;
	}

	int32_t date::sec() const
	{
		return m_tm.tm_sec;
	}

	void date::sec(int32_t _sec)
	{
		m_tm.tm_sec = _sec;
	}

	int32_t date::msec() const
	{
		return m_msec;
	}

	void date::msec(int32_t _msec)
	{
		m_msec = _msec;
	}

	int32_t date::week() const
	{
		return m_tm.tm_wday == 0 ? 7 : m_tm.tm_wday;
	}

	int32_t date::get_days_in_month()
	{
		int32_t d;
		int32_t day[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		if (2 == month())
		{
			d = ((((0 == year() % 4) && (0 != year() % 100)) || (0 == year() % 400)) ? 29 : 28);
		}
		else
		{
			d = day[month() - 1];
		}
		return d;
	}
	std::string date::to_string()
	{
		std::ostringstream oss;
		oss << std::setfill('0') << std::setw(4) << year()
			<< "-" << std::setw(2) << month()
			<< "-" << std::setw(2) << day()
			<< " " << std::setw(2) << hour()
			<< ":" << std::setw(2) << minute()
			<< ":" << std::setw(2) << sec();

		return oss.str();
	}
}